package com.tvunetworks.device.extra.service.impl;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.tvunetworks.center.common.constant.LocalConstant;
import com.tvunetworks.center.common.exception.ServerException;
import com.tvunetworks.center.common.util.JsonUtil;
import com.tvunetworks.center.common.util.MyUtil;
import com.tvunetworks.device.extra.constants.ResultConstant;
import com.tvunetworks.device.extra.model.BucketInfo;
import com.tvunetworks.device.extra.model.param.ChooseRegionParam;
import com.tvunetworks.device.extra.service.HttpService;
import com.tvunetworks.device.extra.util.AccessServerUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;

/**
 * @author liam
 */
@Service
@Slf4j
public class HttpServiceImpl implements HttpService {

    @Value("${device-extra.instance.chooseRegion.url:http://10.12.22.93/instance/instance-manage/api/region/chooseRegion}")
    private String chooseRegion;

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private AccessServerUtil accessServerUtil;

    @Override
    public BucketInfo chooseRegion(ChooseRegionParam param) {


        String url = chooseRegion;

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        try {
            headers.add(LocalConstant.API_HEADER_PARAM_KEY, accessServerUtil.generatorAccess());
        } catch (IOException e) {
            log.error("chooseRegion get access failed: [{}]", e.getMessage());
            return new BucketInfo();
        }
        ResponseEntity<String> responseEntity = null;
        log.error("output2broadcast>>>>>>>output2broadcast call singular output2broadcastUrl:[{}]", url);
        try {
            HttpEntity<String> httpEntity = new HttpEntity<>(JsonUtil.toJsonStr(param), headers);
            responseEntity = restTemplate.postForEntity(url, httpEntity, String.class);
        } catch (Exception e) {
            log.error("chooseRegion result chooseRegionUrl:[{}],exception", url, e);
            throw new ServerException(ResultConstant.Region.GOT_DEFAULT_REGION_FAILED);
        }
        log.error("chooseRegion>>>>>>>chooseRegion Url:[{}],result:[{}]", url, responseEntity);
        if (responseEntity.getStatusCode() != HttpStatus.OK) {
            throw new ServerException(ResultConstant.Region.GOT_DEFAULT_REGION_FAILED);
        }

        JsonNode jsonNode = null;
        BucketInfo bucketInfo = new BucketInfo();
        try {
            jsonNode = MyUtil.MAPPER.readTree(responseEntity.getBody());
            if (!(jsonNode.has("errorCode") && "0x0".equalsIgnoreCase(jsonNode.get("errorCode").asText()))) {
                log.error("chooseRegion: when trying to get default region. not success url:{} pram:[{}] result:[{}]", url, param, responseEntity.getBody());
                throw new ServerException(ResultConstant.Region.GOT_DEFAULT_REGION_FAILED);
            }
            String region = jsonNode.get("result") == null? null: jsonNode.get("result").asText();
            bucketInfo.setRegion(region);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        return bucketInfo;
    }
}
